from django.http import HttpResponse,JsonResponse
from django.shortcuts import render
import pandas as pd
import numpy as np
from pathlib import Path
from django.db import models

# 获取当前工作目录
current_directory = Path.cwd()

# Create your views here.
from app1.models import Books, Meta

# print("current_directory")
# print(current_directory)
# print("current_directoryend")
# 'ALL', 'VCM', 'FB', 'EC'
# ALL_meta=pd.read_csv(current_directory.joinpath('./app1/all_meta.csv'))
gene_exp = {}
gene_exp['ALL']=np.load(current_directory.joinpath('./app1/all_gene_exp.npy'))
# gene_exp['EC']=np.load(current_directory.joinpath('./app1/ec_exp.npy'))
gene_exp['VCM']=np.load(current_directory.joinpath('./app1/vcm_gene_exp.npy'))
# gene_exp['FB']=np.load(current_directory.joinpath('./app1/fb_exp.npy'))

orders = current_directory.joinpath('./app1/gene_order.txt').read_text().splitlines()
# print(orders)
# coor=np.load(current_directory.joinpath('./app1/coor.npy'))

# meta.loc[:,'MYBPC3']=gene_exp[:,0]
# meta.loc[:,'PCDH7']=gene_exp[:,1]
# meta.loc[:,'FHL2']=gene_exp[:,2]

# meta=meta.sample(5000,replace=False)




def index(request):
    res={
        'status':'ok',
        'data':{
            'UMAP_1':[1,2,3,4,5],
            'UMAP_2':[2,3,4,5,6]

        }
    }
    return JsonResponse(res)


def add_book(request):
    b_name='cook_book'
    b_price=108
    book =Books()
    book.b_name=b_name
    book.b_price=b_price
    book.save()
    return HttpResponse(f'书记添加成功:{book.id}')


def get_book(request):
    books=Books.objects.all()
    for book in books:
        print(book.id,book.b_name,book.b_price)
    return render(request,'Book.html',context={'books':books})


def add_book_page(request):
    return render(request,'add_book_page.html')


def add_book_fun(request):
    b_name=request.POST.get('b_name')
    b_price=request.POST.get('b_price')

    book=Books()
    book.b_name=b_name
    book.b_price=b_price
    book.save()
    return HttpResponse(f'书籍添加成功{book.id}')


def get_data(request):
    gene = request.GET.get('gene', 'MYBPC3')  # Default to 'MYBPC3' if not provided
    data_name = request.GET.get('data_name')
    subcluster = request.GET.get('subcluster')

    # Fetch the relevant metadata
    metaData = Meta.objects.filter(subcluster=subcluster,data_name=data_name).order_by('order')
    if not metaData.exists():
        return JsonResponse({'error': 'No data found for the given subcluster and data_name'}, status=400)
    # , data_name=data_name
    # 根据 subcluster 获取对应的基因表达数据
    current_gene_exp = gene_exp.get(subcluster)  # Use .get() to avoid KeyError
    # 得到metaData的order字段转为数组
    order_list=list(metaData.values_list('order',flat=True))
    if order_list:
        try:
            current_gene_exp = current_gene_exp[order_list, :]
        except IndexError:
            return JsonResponse({'error': 'Invalid row indices'}, status=400)
    if current_gene_exp is None:
        return JsonResponse({'error': 'Invalid subcluster'}, status=400)
    # 将 metaData 转换为 DataFrame
    metaData_df = pd.DataFrame(list(metaData.values()))  # 将 QuerySet 转换为 DataFrame
        # Check if 'cell_states' column exists
    if 'cell_states' not in metaData_df.columns:
        return JsonResponse({'error': "'cell_states' column not found"}, status=400)

    print(current_gene_exp.shape[0],metaData_df.shape[0])
    if current_gene_exp.shape[0] == metaData_df.shape[0]:
        # 将 orders 中的每一项作为新列添加到 metaData_df
        gene_exp_df = pd.DataFrame(current_gene_exp, columns=orders)
        # 使用 pd.concat 一次性将所有列合并到 metaData_df
        metaData_df = pd.concat([metaData_df, gene_exp_df], axis=1)

    res = [[], [], []]
    for i in metaData_df['cell_states'].value_counts().index:
            cur_data=metaData_df[metaData_df['cell_states']==i]
            cur_res={}
            x=[float(i) for i in cur_data['UMAP_1'].values]
            y=[float(i) for i in cur_data['UMAP_2'].values]
            cur_res['x']=x
            cur_res['y']=y
            cur_res['mode']='markers'
            cur_res['name']=i
            cur_res['opacity']=1
            res[0].append(cur_res)
    for i in metaData_df['region'].value_counts().index:
        cur_data=metaData_df[metaData_df['region']==i]
        cur_res={}
        x=[float(i) for i in cur_data['UMAP_1'].values]
        y=[float(i) for i in cur_data['UMAP_2'].values]
        cur_res['x']=x
        cur_res['y']=y
        cur_res['mode']='markers'
        cur_res['name']=i
        cur_res['opacity']=1
        res[1].append(cur_res)
    for i in metaData_df['cell_states'].value_counts().index:
        cur_data=metaData_df[metaData_df['cell_states']==i]
        cur_res={}
        x=[float(i) for i in cur_data['UMAP_1'].values]
        y=[float(i) for i in cur_data['UMAP_2'].values]
        cur_res['x']=x
        cur_res['y']=y
        cur_res['mode']='markers'
        cur_res['name']=i
        cur_res['opacity']=1
        cur_res['marker']={'color':[float(i) for i in cur_data.loc[:,gene].values]}
        res[2].append(cur_res)
    return JsonResponse(res,safe=False)


def test_register(request):
    name=request.POST.get('username')
    password=request.POST.get('password')
    res={
        'name':name,
        'password':password,
        'status':200
    }
    return JsonResponse(res)

def home(request):
    data_names=Meta.objects.values('data_name').distinct()
    subclusters=Meta.objects.values('subcluster').distinct()
    context = {
        'cell_states': ['sample','donor','age','condition','region','race','sex','cell_states'], 
        # 固定字段
        'subclusters': [i['subcluster'] for i in subclusters], 
        'data_names': [i['data_name'] for i in data_names],
        # 'features': orders
        'features': []
    }
    return render(request, 'index.html', context)


def get_features(request):
    search_query = request.GET.get('search', '')  # 获取搜索关键词
    page = int(request.GET.get('page', 1))  # 获取当前页码，默认为1
    page_size = int(request.GET.get('page_size', 10))  # 获取每页条目数，默认为10

    # 过滤特征数据
    filtered_features = [feature for feature in orders if search_query.lower() in feature.lower()]

    # 进行分页
    start_index = (page - 1) * page_size
    end_index = start_index + page_size
    paginated_features = filtered_features[start_index:end_index]

    # 计算总页数
    total_pages = (len(filtered_features) + page_size - 1) // page_size  # 向上取整

    return JsonResponse({
        'features': paginated_features,
        'totalPages': total_pages
    }, safe=False)


def get_chart_data(request):
    if request.method == 'POST':
        subcluster = request.POST.get('subcluster')
        data_name = request.POST.get('data_name')

        # 这里可以根据 subcluster 和 data_name 获取数据
        # 示例数据
        chart_data = {
            'x': [1, 2, 3, 4],
            'y': [10, 15, 13, 17],
            'type': 'scatter',
            'mode': 'markers',
            'marker': {'size': 12}
        }

        return JsonResponse(chart_data)